/** 
 * Interface with h5s websocket pb ctonrol API
 * @constructor
 * @param 
 var pbconf1 = {
	begintime: '2019-03-23T120101+08',//{string} begintime 0 for fileplayback
	endtime: '2019-03-23T150101+08',//{string} endtime 0 for fileplayback
	serverpb: 'true', //'true' or 'false' playback from h5stream record, default false 
	filename: 'token1.mp4', // file name need to playback (begintime == 0 & endtime == 0 and serverpb is true)
	callback: PlaybackCB, //{function}(event(string), userdata(object)) 
	userdata:  user data // user data
};
 
 var conf = {
	protocol: window.location.protocol, // {string} - 'http:' or 'https:'
	host: window.location.host, //{string} - 'localhost:8080'
	rootpath:window.location.pathname, // {string} - path of the app running
	token:'token1', // {string} - token of stream
	streamprofile: 'main', // {string} - stream profile, main/sub or other predefine transcoding profile
	pbconf: pbconf1, //This is optional, if no pbconf, this will be live.
	session:'c1782caf-b670-42d8-ba90-2244d0b0ee83', //{string} - session got from login
	consolelog: 'true' // 'true' or 'false' enable/disable console.log
};                     
*/

function H5sPbControl(conf)
{
	this.wsSocket;
	this.keepaliveTimerId;
	this.bDisConnected = false;
	
	this._debug = true;	
	if (conf.consolelog !== undefined)
	{
		if (conf.consolelog === 'false')
		{
			this._debug = false;	
		}
	}	
	
	this._conf = conf;
	if(this._debug === true) console.log("[PBCONTROL] Websocket Conf:", conf);
	
	this._pbconf = conf.pbconf;
	
	this._token = conf.token;
}
	
H5sPbControl.prototype.H5SWebSocketClient = function(h5spath) 
{
	var socket;
	if(this._debug === true) console.log("[PBCONTROL] H5SWebSocketClient");
	try {
		//alert(this._conf.protocol);
		if (this._conf.protocol == "http:") 
		{
			if (typeof MozWebSocket != "undefined")
			{
				socket = new MozWebSocket('ws://' + this._conf.host  +  h5spath);
			}else
			{
				socket = new WebSocket('ws://' + this._conf.host +  h5spath);
			}
		}
		if (this._conf.protocol == "https:")
		{	
			//alert(this._conf.host);
			if(this._debug === true) console.log(this._conf.host);
			if (typeof MozWebSocket != "undefined")
			{
				socket = new MozWebSocket('wss://' + this._conf.host +  h5spath);
			}else
			{
				socket = new WebSocket('wss://' + this._conf.host + h5spath);
			}				
		}
		if(this._debug === true) console.log(this._conf.host);
	} catch (e) {
		alert('error');
		return;
	}
	return socket;
}

H5sPbControl.prototype.keepaliveTimer = function()	
{
	try {
		var j = {};
		j.cmd = "H5_KEEPALIVE";
		this.wsSocket.send(JSON.stringify(j));
	} catch (e) {
	  if(this._debug === true) console.log(e);
	}
}

H5sPbControl.prototype.onWebSocketData = function(msg)	
{	
	if(typeof msg.data === 'string')
	{
		if(this._debug === true) console.log("[PBCONTROL] string");
		if (this._pbconf != undefined && this._pbconf.callback != undefined)
		{
			this._pbconf.callback(msg.data, this._pbconf.userdata);
		}
		return;
	}
	
	if (this.bDisConnected === true)
	{
		return;
	}
} 

H5sPbControl.prototype.setupWebSocket = function(token)	
{
	var h5spath = "api/v1/h5spbcontrolapi";
	var streamprofile = 'main';
	if (this._conf.streamprofile === undefined)
	{}else 
	{
		streamprofile = this._conf.streamprofile;
	}
	
	if (this._pbconf === undefined)
	{
		h5spath = this._conf.rootpath + h5spath + "?token=" + token 
						+ "&profile=" + streamprofile + '&session=' + this._conf.session;
	}else 
	{
		var serverpb = 'false';
		var filename = 'fake';
		if (this._pbconf.serverpb === undefined)
		{}else 
		{
			serverpb = this._pbconf.serverpb;
		}

		if (this._pbconf.filename === undefined)
		{}else 
		{
			filename = this._pbconf.filename;
		}		
		
		h5spath = this._conf.rootpath + h5spath + "?token=" + token 
								+ "&playback=true"
								+ '&profile=' + streamprofile
								+ "&serverpb=" + serverpb
								+ "&begintime=" + encodeURIComponent(this._pbconf.begintime)//this._pbconf.begintime
								+ "&endtime=" + encodeURIComponent(this._pbconf.endtime)//this._pbconf.endtime
								+ "&filename=" + filename//file name
								+ '&session=' + this._conf.session;
	}				+ '&session=' + this._conf.session;

	
	
	if(this._debug === true) console.log(h5spath);
	
	this.wsSocket = this.H5SWebSocketClient(h5spath);
	if(this._debug === true) console.log("[PBCONTROL] setupWebSocket", this.wsSocket);
	this.wsSocket.binaryType = 'arraybuffer';
	this.wsSocket.h5 = this;
	this.wsSocket.onmessage = this.onWebSocketData.bind(this);
	
	this.wsSocket.onopen = function()
	{
		if(this.h5._debug === true) console.log("[PBCONTROL] wsSocket.onopen", this.h5);
		this.h5.keepaliveTimerId = setInterval(this.h5.keepaliveTimer.bind(this.h5), 1000);

		var j = {};
		j.type = "H5S_WS_CONNECTED";
		if (this.h5._pbconf != undefined && this.h5._pbconf.callback != undefined)
		{
			this.h5._pbconf.callback(JSON.stringify(j), this.h5._pbconf.userdata);
		}
	}
	
	this.wsSocket.onclose = function () {
		if(this.h5._debug === true) console.log("[PBCONTROL] wsSocket.onclose", this.h5);
		
		var j = {};
		j.type = "H5S_WS_DISCONNECTED";
		if (this.h5._pbconf != undefined && this.h5._pbconf.callback != undefined)
		{
			this.h5._pbconf.callback(JSON.stringify(j), this.h5._pbconf.userdata);
		}
		
		this.h5.CleanupWebSocket(this.h5);
	}

}
	
H5sPbControl.prototype.CleanupWebSocket = function(h5sPlayer)
{
	if(h5sPlayer._debug === true) console.log('[PBCONTROL] CleanupWebSocket', h5sPlayer);
	clearInterval(h5sPlayer.keepaliveTimerId);
}


/** 
 * Connect a websocket Stream to videoElement 
*/
H5sPbControl.prototype.connect = function() {
	/* start connect to server */
	this.setupWebSocket(this._token);
}


/** 
 * Disconnect a websocket Stream and clear videoElement source
*/
H5sPbControl.prototype.disconnect = function() {
	if(this._debug === true) console.log("[PBCONTROL] disconnect", this);
	this.bDisConnected = true;
	clearInterval(this.reconnectTimerId);
	
	try {
		if (this.wsSocket != null)
		{
			this.wsSocket.close();
			this.wsSocket = null;
		}
	}
	catch (e){}
	
	if(this._debug === true) console.log("[PBCONTROL] disconnect", this);
}

H5sPbControl.prototype.start = function(){
	try {
		var j = {};
		j.cmd = "H5_START";
		this.wsSocket.send(JSON.stringify(j));
	} catch (e) {
	  if(this._debug === true) console.log(e);
	}
}

H5sPbControl.prototype.pause = function(){
	try {
		var j = {};
		j.cmd = "H5_PAUSE";
		this.wsSocket.send(JSON.stringify(j));
	} catch (e) {
	  if(this._debug === true) console.log(e);
	}
}

H5sPbControl.prototype.resume = function(){
	try {
		var j = {};
		j.cmd = "H5_RESUME";
		this.wsSocket.send(JSON.stringify(j));
	} catch (e) {
	  if(this._debug === true) console.log(e);
	}
}

H5sPbControl.prototype.seek = function(nTime){
	try {
		var j = {};
		j.cmd = "H5_SEEK";
		j.nSeekTime = nTime;
		this.wsSocket.send(JSON.stringify(j));
	} catch (e) {
	  if(this._debug === true) console.log(e);
	}
}

H5sPbControl.prototype.speed = function(nSpeed){
	try {
		var j = {};
		j.cmd = "H5_SPEED";
		j.nSpeed = nSpeed;
		this.wsSocket.send(JSON.stringify(j));
	} catch (e) {
	  if(this._debug === true) console.log(e);
	}
}
